<template>
  <div class="album-detail">
    <!-- 头部信息 -->
    <div class="album-header">
      <div class="header-content">
        <div class="back-button" @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
          返回相册列表
        </div>
        <div class="album-info">
          <h1 class="album-title">{{ album?.name }}</h1>
          <p class="album-desc">{{ album?.description || "暂无描述" }}</p>
          <div class="album-meta">
            <span class="photo-count">
              <el-icon><Picture /></el-icon>
              {{ album?.photos?.length || 0 }} 张图片
            </span>
            <span class="create-time">
              <el-icon><Clock /></el-icon>
              {{ formatDate(album?.createTime) }}
            </span>
          </div>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showAddImages">
            <el-icon><Plus /></el-icon>
            添加图片
          </el-button>
        </div>
      </div>
    </div>

    <!-- 图片网格 -->
    <div class="photo-grid" v-loading="loading">
      <el-empty
        v-if="!loading && (!album?.photos || album.photos.length === 0)"
        description="暂无图片，点击右上角添加"
      />

      <div
        v-for="photo in album?.photos"
        :key="photo.id"
        class="photo-item"
        @click="previewImage(photo)"
      >
        <el-image
          :src="getFullImageUrl(photo.file_path)"
          fit="cover"
          loading="lazy"
        >
          <template #error>
            <div class="image-error">
              <el-icon><Picture /></el-icon>
              <span>加载失败</span>
            </div>
          </template>
        </el-image>
        <div class="photo-info">
          <span class="photo-name">{{ photo.file_name }}</span>
          <div class="photo-tags">
            <el-tag
              v-for="tag in JSON.parse(photo.tags)"
              :key="tag"
              size="small"
              class="tag"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
      </div>
    </div>

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="showViewer"
      :url-list="previewUrls"
      :initial-index="currentPreviewIndex"
      @close="showViewer = false"
    />

    <!-- 添加图片对话框 -->
    <AlbumImageDialog
      v-if="album"
      v-model:visible="showAddImagesDialog"
      :album-id="album.id"
      @added="handleImagesAdded"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { format } from "date-fns";
import { ArrowLeft, Picture, Clock, Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import axios from "axios";
import AlbumImageDialog from "../components/AlbumImageDialog.vue";

interface Photo {
  id: number;
  file_name: string;
  file_path: string;
  tags: string;
}

interface Album {
  id: number;
  name: string;
  description?: string;
  createTime: string;
  photos: Photo[];
}

const route = useRoute();
const router = useRouter();
const album = ref<Album | null>(null);
const loading = ref(false);
const showViewer = ref(false);
const previewUrls = ref<string[]>([]);
const currentPreviewIndex = ref(0);
const showAddImagesDialog = ref(false);

// 获取相册详情
const fetchAlbumDetail = async () => {
  const albumId = route.params.id;
  if (!albumId) return;

  loading.value = true;
  try {
    const response = await axios.get(
      `http://localhost:3000/albums/${albumId}/images`
    );
    const albumResponse = await axios.get(
      `http://localhost:3000/albums/${albumId}`
    );

    album.value = {
      ...albumResponse.data,
      photos: response.data,
    };
  } catch (error) {
    console.error("获取相册详情失败:", error);
    ElMessage.error("获取相册详情失败");
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return "";
  return format(new Date(dateStr), "yyyy-MM-dd HH:mm");
};

// 获取完整的图片URL
const getFullImageUrl = (path: string) => {
  return `http://localhost:3000/${path}`;
};

// 返回相册列表
const goBack = () => {
  router.push("/albums");
};

// 显示添加图片对话框
const showAddImages = () => {
  showAddImagesDialog.value = true;
};

// 处理图片添加成功
const handleImagesAdded = () => {
  fetchAlbumDetail();
};

// 预览图片
const previewImage = (photo: Photo) => {
  if (!album.value?.photos) return;

  previewUrls.value = album.value.photos.map((p) =>
    getFullImageUrl(p.file_path)
  );
  currentPreviewIndex.value = album.value.photos.findIndex(
    (p) => p.id === photo.id
  );
  showViewer.value = true;
};

onMounted(() => {
  fetchAlbumDetail();
});
</script>

<style scoped lang="scss">
.album-detail {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px;
}

.album-header {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;

  .header-content {
    padding: 24px;
    display: flex;
    align-items: flex-start;
    gap: 24px;
  }

  .back-button {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #606266;
    cursor: pointer;
    padding: 8px;
    border-radius: 4px;
    transition: all 0.3s;

    &:hover {
      background: #f5f7fa;
      color: #409eff;
    }
  }

  .album-info {
    flex: 1;

    .album-title {
      margin: 0 0 8px;
      font-size: 24px;
      color: #303133;
    }

    .album-desc {
      margin: 0 0 16px;
      color: #606266;
      font-size: 14px;
    }

    .album-meta {
      display: flex;
      gap: 16px;
      color: #909399;
      font-size: 14px;

      span {
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  padding: 8px;
}

.photo-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  }

  .el-image {
    width: 100%;
    height: 250px;
  }

  .photo-info {
    padding: 12px;

    .photo-name {
      display: block;
      font-size: 14px;
      color: #303133;
      margin-bottom: 8px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .photo-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;

      .tag {
        font-size: 12px;
      }
    }
  }
}

.image-error {
  height: 250px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;

  .el-icon {
    font-size: 24px;
    margin-bottom: 8px;
  }
}

@media (max-width: 768px) {
  .album-header {
    .header-content {
      flex-direction: column;
      gap: 16px;
    }

    .album-info {
      .album-title {
        font-size: 20px;
      }
    }

    .header-actions {
      width: 100%;
      justify-content: flex-end;
    }
  }

  .photo-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
  }
}
</style>
